import { whiteListFilter } from "@/utils";

export const defendMyRoom = {

    run: function (room) {

        var hostiles = room.find(FIND_HOSTILE_CREEPS)
        var towers: StructureTower[] = room.find(FIND_MY_STRUCTURES, { filter: { structureType: STRUCTURE_TOWER } })

        //if there are hostiles - attakc them
        if (hostiles.length > 0) {
            var username = hostiles[0].owner.username;
            Game.notify(`User ${username} spotted in room ${room.name}`);
            towers.forEach(tower => {
                if (hostiles[0]) {
                    const creep: Creep = hostiles[0]
                    if (!whiteListFilter(creep)) {
                        return
                    }
                }
                tower.attack(hostiles[0])
                console.log('[' + tower.room.name + "] ALERT!!!! WE ARE UNDER ATTACK!!!!! ALERT!!!! WE ARE UNDER ATTACK!!!!! ALERT!!!! WE ARE UNDER ATTACK!!!!! ")
            });
        }
        else {
            const storage = room[STRUCTURE_STORAGE]
            if (storage) {
                const damagedRampart = storage.pos.findClosestByRange(FIND_STRUCTURES, { filter: (s) => s.hits < 10000 && s.structureType == STRUCTURE_RAMPART });

                //....first heal any damaged creeps
                // for (let name in Game.creeps) {
                //     // get the creep object
                //     var creep = Game.creeps[name];
                //     if (creep.hits < creep.hitsMax) {
                //         towers.forEach(tower => tower.heal(creep));
                //         // console.log("Tower is healing Creeps.");
                //     }
                // }

                for (var i in towers) {
                    //...repair Buildings! :) But ONLY until HALF the energy of the tower is gone.
                    //Because we don't want to be exposed if something shows up at our door :)
                    if (towers[i].store.energy > ((towers[i].store.getCapacity(RESOURCE_ENERGY) / 10) * 9)) {

                        //Find the closest damaged Structure
                        // var closestDamagedStructure = towers[i].pos.findClosestByRange(FIND_STRUCTURES, { filter: (s) => s.hits < s.hitsMax && s.structureType != STRUCTURE_WALL && s.structureType != STRUCTURE_RAMPART });
                        // if (closestDamagedStructure) {
                        //     towers[i].repair(closestDamagedStructure);
                        //     // console.log("The tower is repairing buildings.");
                        // }
                        // else {
                        //Find the closest damaged Structure
                        if (damagedRampart && damagedRampart.hits < 10000) {
                            towers[i].repair(damagedRampart);
                        }
                        // }
                    }
                }
            }
        }
    }
}
